<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="校区" prop="schoolName">
        <el-input v-model="queryParams.schoolName" readonly="readonly" @click.native="openSelectSchool(1)"
          placeholder="请输入校区" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="续费周期" prop="calcMonth">
        <el-input v-model="queryParams.calcMonth" placeholder="请输入续费周期如(2025Q3)" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="付款" prop="payState">
        <el-select v-model="queryParams.payState" placeholder="付款" clearable>
          <el-option v-for="dict in dict.type.common_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-edit" size="mini" :disabled="multiple" @click="handleConfirm"
          v-hasPermi="['report:pay:confirm']">确认收款</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['report:chargeorder:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chargeorderList" @selection-change="handleSelectionChange"
      :span-method="mergeOperRow">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计费周期" align="center" prop="calcMonth">
      </el-table-column>
      <el-table-column label="学校全称" align="center" prop="schoolName" />
      <el-table-column label="联系人" align="center" prop="contacts" />
      <el-table-column label="联系电话" align="center" prop="tel" />
      <el-table-column label="招生人数" align="center" prop="stuNum" />
      <el-table-column label="续费类型" align="center" prop="renewType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.stu_member_type" :value="scope.row.renewType" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="新招">
        <el-table-column label="总人数" align="center" prop="addStuNum" />
        <el-table-column label="总佣金(元)" align="center" prop="addStuAmount" />
      </el-table-column>

      <el-table-column align="center" label="续费">
        <el-table-column label="总人数" align="center" prop="renewStuNum" />
        <el-table-column label="总佣金(元)" align="center" prop="renewStuAmount" />
      </el-table-column>
      <el-table-column label="总佣金(元)" align="center" prop="orderAmount" />
      <el-table-column label="付款" align="center" prop="payState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_state" :value="scope.row.payState" />
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-info"
            @click="openDetail(scope.row,'order-month-index')">月份详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-info"
            @click="openDetail(scope.row,'order-month-detail')">订单详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 选择校区 -->
    <SelectSchool ref="selectSchool" :open="selectFlag" @selected-data="selectSchoolData"
      @close-select-window="closeSelectSchool" />
    <order-month-index ref="order-month-index"></order-month-index>
    <order-month-detail ref="order-month-detail"></order-month-detail>
  </div>
</template>

<script>
  import {
    listChargeorder,
    getChargeorder,
    confirmOrder
  } from "@/api/bus_web/report/chargeorder";
  import SelectSchool from "../../school/schoolinfo/select.vue"
  import OrderMonthIndex from "./order_month_index.vue"
  import OrderMonthDetail from "./order_month_detail.vue"
  import {
    mapState
  } from 'vuex';
  import store from "@/store";
  export default {
    name: "Chargeorder",
    dicts: ['stu_member_type', 'common_state'],
    components: {
      SelectSchool,
      OrderMonthIndex,
      OrderMonthDetail
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 是否显示校区选择
        selectFlag: false,
        // 提交处理中标记
        submitLoading: false,
        // 总条数
        total: 0,
        // 收费订单表格数据
        chargeorderList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          startDate: null,
          endDate: null,
          deleted: null,
          schoolId: null,
          payState: null,
          amount: null,
          gmtCreate: null,
          gmtModify: null,
          doUserId: null,
          doTime: null,
          doRemark: null,
          schoolName: null,
          schoolIdArray: []
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {}
      };
    },
    computed: {
      ...mapState({
        school: state => state.selectSchool.school,
        schoolSelectModel: state => state.selectSchool.schoolSelectModel,
      })
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询收费订单列表 */
      getList() {
        this.loading = true;
        listChargeorder(this.queryParams).then(response => {
          this.chargeorderList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.calculateMergeSpan('id')
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          startDate: null,
          endDate: null,
          deleted: null,
          schoolId: null,
          payState: null,
          amount: null,
          gmtCreate: null,
          gmtModify: null,
          doUserId: null,
          doTime: null,
          doRemark: null
        };
        this.resetForm("form");
        this.queryParams.schoolIdArray = []
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.queryParams.schoolIdArray = []
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.billId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 确认收款 */
      handleConfirm(row) {
        const ids = row.billId || this.ids;
        this.$modal.confirm('确定将选中订单改为已付款吗？').then(function() {
          return confirmOrder(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("确认收款成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('report/chargeorder/export', {
          ...this.queryParams
        }, `账单信息_${new Date().getTime()}.xlsx`)
      },
      //选择校区
      openSelectSchool(selectVal) {
        this.selectFlag = true
        // selectVal =1 查询模式 =2 创建、修改模式
        this.$store.dispatch('selectSchool/cleanSchool')
        this.$store.dispatch('selectSchool/setSchoolSelectModel', selectVal)
      },
      closeSelectSchool() {
        this.selectFlag = false
      },
      //确定校区
      selectSchoolData() {
        this.closeSelectSchool()
        if (this.schoolSelectModel == 2) {
          this.form.schoolName = this.school[0].schoolName
          this.form.schoolId = this.school[0].id
          this.$refs.form.clearValidate(['schoolName']);
        } else {
          this.queryParams.schoolName = this.school.map(item => item.schoolName).join(',')
          this.queryParams.schoolIdArray = this.school.map(item => item.id)
        }
        this.$store.dispatch('selectSchool/cleanSchool')
      },
      // 明细tab
      openDetail(row, op) {
        this.$nextTick(() => {
          this.$refs[op].init(row)
        })
      },
      // 计算合并信息：基于 field 字段的连续相同值
      calculateMergeSpan(field) {
        const spans = [];
        const data = this.chargeorderList;
        let i = 0;
        while (i < data.length) {
          let j = i;
          // 找出从 i 开始连续相同值的结束位置
          while (j < data.length && data[j][field] === data[i][field]) {
            j++;
          }
          const count = j - i;
          // 第一个位置记录 rowspan，其余标记为隐藏
          spans[i] = count;
          for (let k = i + 1; k < j; k++) {
            spans[k] = 0;
          }
          i = j;
        }
        this.mergeSpan = spans;
      },
      //合并第一列
      mergeOperRow({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        // 只对“姓名”列（columnIndex === 1）应用合并
        if (columnIndex == 0 || columnIndex == 1 || columnIndex == 2 || columnIndex == 3 || columnIndex == 13) {
          const rowspan = this.mergeSpan[rowIndex];
          return {
            rowspan,
            colspan: rowspan > 0 ? 1 : 0
          };
        }
        // 其他列不合并
        return {
          rowspan: 1,
          colspan: 1
        };
      }
    }
  };
</script>
